import os
import random
from math import sqrt

# game constants
from constants import *

# cocos componets used by this scene
from cocos.director import director
from cocos.scene import Scene
from cocos.layer import Layer, ColorLayer
from cocos.scenes.transitions import *
from cocos.actions import *
from cocos.sprite import Sprite
from cocos.text import Label
from cocos.cocosnode import CocosNode
from cocos.batch import BatchNode
from cocos.draw import Line

# pyglet  componets used by this scene
import pyglet
from pyglet import gl, font
from pyglet.window import key
from pyglet.gl import *

import kytten


class LaunchShipDialog(Layer):
    is_event_handler = True     #: enable pyglet's events
    
    def __init__(self,galaxy,fromPlanet,toPlanet=None):
        super( LaunchShipDialog, self ).__init__()
        
        self.interface = galaxy.interface
        self.galaxy = galaxy
        self.fromPlanet = fromPlanet
        self.toPlanet = toPlanet  
              
        self.population = 0
        self.organics = 0
        self.minerals = 0 
        self.soldierNumber = 0
        
        self.fuelNeeded = self._distance(self.fromPlanet.position,self.toPlanet.position)
        
        
        # add a semi transparent bg
        self.add(ColorLayer(0,0,0,120),z=-2)
        
        director.window.register_event_type('on_update')        
        def update(dt):
            director.window.dispatch_event('on_update', dt)         
            
            if self.sliders[1].get_value() < self.fuelNeeded:
                self.fuelLabel.element.color = (255,0,0,255)
                self.okbutton.delete()
            else:
                self.fuelLabel.element.color = (0,200,0,250)
                self.okbutton.saved_dialog.set_needs_layout()
                
            self.soldiersLabel.element.text = str(self.soldierNumber)
            self.mineralsLabel.element.text = str(self.minerals)
            self.peopleLabel.element.text = str(self.population)
            self.organicsLabel.element.text = str(self.organics)
            

        self.schedule(update)
        

        self.batchnode = BatchNode()
        self.add(self.batchnode)

        
        self.dialog = kytten.Dialog(
	            kytten.Frame(
	                kytten.VerticalLayout([
		                kytten.Label("Launch Ship"),
                        kytten.HorizontalLayout([
                            None,
                            kytten.VerticalLayout([
                                kytten.Label("From"),
                                kytten.Label("planet"),
                                kytten.Label(self.fromPlanet.name)
                            ]),None,
                            kytten.VerticalLayout([
                                kytten.Label("To"),
                                kytten.Label("planet"),
                                kytten.Label(self.toPlanet.name)
                            ]),
                            None,
                        ]),
                        None,None,None,
                        kytten.HorizontalLayout([
                            kytten.VerticalLayout([
                                kytten.Label("Minerals"),    
                                kytten.Slider(0, 0.0, SHIP_CARGO_SPACE, steps=SHIP_CARGO_SPACE, on_set=self.setMinerals),
                            ]),
                            kytten.VerticalLayout([
                                kytten.Label("Organics/Fuel"),    
                                kytten.Slider(min(self.fuelNeeded,self.fromPlanet.organics), 0.0, SHIP_CARGO_SPACE, steps=SHIP_CARGO_SPACE, on_set=self.setOrganics),
                            ]),
                            kytten.VerticalLayout([
                                kytten.Label("People"),    
                                kytten.Slider(0, 0.0, SHIP_CARGO_SPACE, steps=SHIP_CARGO_SPACE, on_set=self.setPeople),
                            ]),
                            kytten.VerticalLayout([
                                kytten.Label("Soldiers"),    
                                kytten.Slider(0, 0.0, SHIP_CARGO_SPACE, steps=SHIP_CARGO_SPACE, on_set=self.setSoldiers),
                            ]),
                        ]),
                        None,None,None,
                        kytten.HorizontalLayout([
                            kytten.Button("Cancel", on_click=self.cancel),
                            None, None,
                            kytten.Button("Launch", on_click=self.launch),
                        ]),
	                ]),
	            ),
	        batch=self.batchnode.batch,window=director.window,theme=KYTTEN_THEME,movable=False)
      
      
        #print self.dialog._get_controls()
        
        self.sliders=[]
        for i in range(4):
            self.sliders += [self.dialog._get_controls()[i][0]]
            
        self.okbutton = self.dialog._get_controls()[5][0]
      
        self.fuelLabel = Label( "Fuel needed: %d" %(self.fuelNeeded),
            font_size=12,
            height=40,
            width=160,
            color=(0,200,0,250),
            bold=True,
            x=director.get_window_size()[0]/2,
            y=director.get_window_size()[1]/2-100,
            anchor_x=font.Text.CENTER,
            anchor_y=font.Text.CENTER )

        self.soldiersLabel = Label( str(self.soldierNumber),
            font_size=12,
            bold=True,
            x=director.get_window_size()[0]/2+195,
            y=director.get_window_size()[1]/2-70)
            
        self.mineralsLabel = Label( str(self.minerals),
            font_size=12,
            bold=True,
            x=director.get_window_size()[0]/2-220,
            y=director.get_window_size()[1]/2-70)
            
        self.peopleLabel = Label( str(self.population),
            font_size=12,
            bold=True,
            x=director.get_window_size()[0]/2+75,
            y=director.get_window_size()[1]/2-70)
            
        self.organicsLabel = Label( str(self.organics),
            font_size=12,
            bold=True,
            x=director.get_window_size()[0]/2-75,
            y=director.get_window_size()[1]/2-70)
            
        self.add( self.fuelLabel )
        
        self.add( self.soldiersLabel )
        self.add( self.mineralsLabel )
        self.add( self.peopleLabel )
        self.add( self.organicsLabel )
        
        self.population = int(self.sliders[2].get_value())
        self.organics = int(self.sliders[1].get_value())
        self.minerals = int(self.sliders[0].get_value())
        self.soldierNumber = int(self.sliders[3].get_value())
        
    def setOrganics(self,val):
        self.sliders[1].set_pos(min(val,self.fromPlanet.organics)*0.01)
        self.adjustSliders(1)

        
    def setMinerals(self,val):
        self.sliders[0].set_pos(min(val,self.fromPlanet.minerals)*0.01)
        self.adjustSliders(0)

            
    def setPeople(self,val):
        self.sliders[2].set_pos(min(val,self.fromPlanet.population)*0.01)
        self.adjustSliders(2)

            
    def setSoldiers(self,val):
        self.sliders[3].set_pos(min(val,len(self.fromPlanet.soldiers)+0.01)*0.01)
        self.adjustSliders(3)
        
            
    def adjustSliders(self,decidingSlider): 

        total = 0
        for slider in self.sliders:
            total += slider.get_value()
            
        if total <= SHIP_CARGO_SPACE: 
            self.population = int(self.sliders[2].get_value())
            self.organics = int(self.sliders[1].get_value())
            self.minerals = int(self.sliders[0].get_value())
            self.soldierNumber = int(self.sliders[3].get_value())
            return
        
        for i in range(len(self.sliders)):
            if i != decidingSlider:
                self.sliders[i].set_pos(self.sliders[i].pos-0.01)
        
        self.adjustSliders(decidingSlider)      
                        
                        
    def on_dummy(self,a):
        print a
        
            
    def launch(self):
        if self.toPlanet != None:
            print "Launch confirmed"
            print self.fromPlanet.launchShip(self.toPlanet,self.minerals,self.organics,self.population,self.soldierNumber)
        self.kill()
            
            
    def cancel(self):
        print "Launch aborted"
        self.kill()
    

    def on_enter(self):
        super( LaunchShipDialog, self ).on_enter() 
        #pause game
        self.galaxy.running = False
        
        
    def on_exit(self):
        super( LaunchShipDialog, self ).on_exit() 
        self.dialog.teardown()
        self.batchnode.on_exit()
        # unpause game
        self.galaxy.running = True
        
    def on_key_press( self, k , m ):
        if k == key.ESCAPE:
            self.cancel()
            return pyglet.event.EVENT_HANDLED # this prevents ESC to pop this scene (default behaviour)

    def _distance(self,start,end):
        return sqrt( (end[0] - start[0])**2 + (end[1] - start[1])**2 )
         
